
layui.use(['form', 'layer', 'table'], function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        table = layui.table;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var save_url = $('.save_url').val();


    if ($(parent.window.frames[0].document).find('input[name=id]').val()) {
        //datalist_url += '?id=' + $(parent.window.frames[0].document).find('input[name=id]').val(); // 编辑商品时，再编辑菜谱会有bug
        datalist_url += '?cookbook_ids=' + $(parent.window.frames[0].document).find('.cookbook_ids').val();
    } else {
        datalist_url += '?cookbook_ids=' + $(parent.window.frames[0].document).find('.cookbook_ids').val();
    }
    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url : datalist_url,
        page : true,
        cellMinWidth : 95,
        //height : "full-100",
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "cookbookTableList",
        cols : [[
            {field: 'img_url', title: '菜谱封面', minWidth:80, align:"center", templet:function(data){
                return '<a href="'+data.img_url+'" target="_blank"><img src="'+data.img_url+'" style="width: 80px;" /></a>';
            }},
            {field: 'name', title: '菜谱名', align:'center'},
            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';

                return html;
            }}
        ]]
    });

    // 搜索
    $(".search_btn").on("click", function(){
        if($('.name').val() != ''){
            table.reload("cookbookTableList", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    name: $('.searchBox').find('input[name=name]').val()  // 搜索的关键字
                }
            });
        }else{
            layer.msg("请输入搜索的内容");
        }
    });

    // 清空搜索
    $(".reset_btn").on("click", function(){
        table.reload("cookbookTableList", {
            where: {
                name: ''
            }
        });
    });

    $('.add_btn').on('click', function(){
        formHtml();
    });

    // 列表操作
    table.on('tool(dataTable)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
                $.ajax({
                    url: delete_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            //tableIns.reload();
                            obj.del();
                            layer.close(index);

                            // 删除菜谱
                            var cookbook_ids_elm = $(parent.window.frames[0].document).find('.cookbook_ids');
                            var cookbook_ids = cookbook_ids_elm.val();
                            var arr = cookbook_ids.split(',');
                            var new_cookbook_ids = '';
                            for(var i = 0; i < arr.length; i++){
                                if(arr[i] != data.id){
                                    new_cookbook_ids += ',' + arr[i];
                                }
                            }

                            cookbook_ids_elm.val(new_cookbook_ids.substr(1));
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if(layEvent === 'edit'){
            formHtml(data);
        }
    });

    // Form 表单
    function formHtml(data){
        var content = add_url;
        if(data){
            content = edit_url + '?id=' + data.id;
        }
        // 右侧面板
        var index = layer.open({
            type: 2
            , anim: -1
            , title: false
            , closeBtn: false
            , offset: 'r'
            , shade: 0.1
            //, shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-adminRight'
            , area: '800px'
            , top: 0
            , content: content
            , success: function () {
                //init_laydate(); // 不生效
            }
        });
    }


    //++ 七牛上传初始化 Begin ++//
    var load_upload_image_arr = [];
    var token_url = $('.token_url').val();
    var record_url = $('.record_url').val();
    var max_file_size = '1MB';
    var extensions = 'jpg,jpeg,gif,png';
    var multi = false;
    var initUploader = function (param) {
        $.ajax({
            url: token_url,
            type: 'POST',
            data: {},
            cache: false,
            contentType: false,    //不可缺
            processData: false,    //不可缺
            dataType : 'json',
            success: function (data) {
                var url = "";
                var qiniupercent = "";

                if(param) {
                    var index = param.index;
                    //var pickfiles = ['upload-btn-'+index];
                    //uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image-'+index, pickfiles, max_file_size, extensions, multi);
                    //if($.inArray('upload-image-'+index, load_upload_image_arr) < 0){
                        uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image-'+index, 'upload-btn-'+index, max_file_size, extensions, multi);

                        //load_upload_image_arr.push('upload-image-'+index);
                    //}
                }
            }
        });
    };
    var uploaderImgReady = function (token, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi) {
        var uploaderForUditor = Qiniu.uploader({
            runtimes: 'html5,flash,html4',
            browse_button: pickfiles,     //上传按钮的ID
            // container: uploader,      //上传按钮的上级元素ID
            // drop_element: uploader,
            max_file_size: max_file_size,         //最大文件限制
            flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
            dragdrop: false,
            chunk_size: '4mb',              //分块大小
            //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
            uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
            // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
            domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
            multi_selection: multi,         //是否允许同时选择多文件
            filters: {
                mime_types: [               //文件类型过滤，这里限制为图片类型
                    {title: "Image files", extensions: extensions}
                ]
            },
            auto_start: true,
            unique_names :true,             //自动生成文件名,如果值为false则保留原文件名上传
            init: {
                'FilesAdded': function (up, files) {
                    plupload.each(files, function(file) {
                        // 文件添加进队列后，处理相关的事情
                    });
                },
                'BeforeUpload': function (up, file) {
                    // 每个文件上传前，处理相关的事情
                    layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                },
                'UploadProgress': function (up, file) {
                    //文件上传时，处理相关的事情

                    //上传进度 class="layui-btn" type="button"

                    //console.log(file.percent + "%");
                },
                'UploadComplete': function () {
                    //do something
                },
                'FileUploaded': function (up, file, info) {
                    //每个文件上传成功后,处理相关的事情,并记录到数据库
                    //其中 info 是文件上传成功后，服务端返回的json，形式如
                    //{
                    //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                    //  "key": "gogopher.jpg"
                    //}
                    var domain = up.getOption('domain');
                    var res = eval('(' + info.response + ')');
                    var sourceLink = domain + res.key;//获取上传文件的链接地址
                    //console.log(sourceLink);
                    $.ajax({
                        url: record_url,
                        type: 'POST',
                        data: {
                            'imgUrl': sourceLink
                        },
                        cache: false,
                        dataType: 'json',
                        success: function (data) {
                            //console.log(data);
                            layer.closeAll('loading'); // 关闭loading
                            if (data.code === '1') {
                                // 删除原图
                                var img_url = $('#' + pickfiles).find('img').attr('src');
                                delOriginalImg(img_url);

                                $('#' + pickfiles).find('img').attr('src', sourceLink);
                                $('#' + pickfiles).find('.step_img_url').val(sourceLink);
                            }
                        }
                    });

                },
                'Error': function (up, err, errTip) {
                    layer.closeAll('loading'); // 关闭loading
                    alert(errTip);
                },
            }
        });
    };
    // 删除原图
    var delOriginalImg = function (img_url) {
        var delimage_url = $('.delimage_url').val();

        $.ajax({
            url: delimage_url,
            type: 'POST',
            data: {
                'imgUrl' : img_url,
            },
            cache: false,
            dataType : 'json',
            success: function (data) {
                //
            }
        });
    };
    //++ 七牛上传初始化 End ++//


    if($('.cookbook_step-group').length > 0){
        $('.cookbook_step-group').find('.step-group').each(function (i) {
            initUploader({'index':i});
        });
    }

    // 添加食材
    $('.addIngredient-btn').on('click', function(){
        var length = $('.ingredients-group').find('.ingredient-group').length;
        var $html = '';
        $html += '<div class="layui-form-item layui-form-text ingredient-group">';
            $html += '<div class="layui-inline">';
                $html += '<label class="layui-form-label"><span class="required">*</span>食材名称</label>';
                $html += '<div class="layui-input-inline">';
                $html += '<input type="text" class="layui-input ingredient_name" name="ingredient_name['+length+']" maxlength="40" placeholder="" autocomplete="off">';
                $html += '</div>';
            $html += '</div>';
            $html += '<div class="layui-inline">';
                $html += '<label class="layui-form-label" style="width: 70px;"><span class="required">*</span>用量</label>';
                $html += '<div class="layui-input-inline">';
                $html += '<input type="text" class="layui-input ingredient_num" name="ingredient_num['+length+']" maxlength="15" placeholder="" autocomplete="off">';
                $html += '</div>';
            $html += '</div>';
            $html += '<div class="layui-inline">';
                $html += '<div class="layui-input-inline">';
                $html += '<button type="button" class="layui-btn layui-btn-danger delIngredient-btn"><i class="layui-icon layui-icon-delete"></i></button>';
                $html += '</div>';
            $html += '</div>';
        $html += '</div>';

        $('.ingredients-group').append($html);
    });
    // 删除食材
    $('.ingredients-group').on('click', '.delIngredient-btn', function(){
        $(this).parents('.ingredient-group').remove();
    });

    // 添加烹饪步骤
    $('.addStep-btn').on('click', function(){
        var length = $('.cookbook_step-group').find('.step-group').length;
        var $html = '';
        $html += '<div class="layui-form-item layui-form-text step-group">';
            $html += '<div class="layui-col-xs5">';
                $html += '<label class="layui-form-label"><span class="required">*</span>步骤图</label>';
                $html += '<div id="upload-image-'+length+'">';
                    $html += '<div class="layui-upload-list thumbBox mag0 magt3" id="upload-btn-'+length+'" data-multi="false">';
                    $html += '<input type="hidden" class="layui-input step_img_url" name="step_img_url['+length+']">';
                    $html += '<img class="layui-upload-img thumbImg">';
                    $html += '</div>';
                $html += '</div>';
            $html += '</div>';
            $html += '<div class="layui-inline">';
                $html += '<label class="layui-form-label" style="width: 70px;"><span class="required">*</span>步骤说明</label>';
                $html += '<div class="layui-input-inline">';
                $html += '<textarea class="layui-textarea content" name="content['+length+']" placeholder=""></textarea>';
                $html += '</div>';
            $html += '</div>';
            $html += '<div class="layui-inline">';
                $html += '<div class="layui-input-inline">';
                $html += '<button type="button" class="layui-btn layui-btn-danger delStep-btn"><i class="layui-icon layui-icon-delete"></i></button>';
                $html += '</div>';
            $html += '</div>';
        $html += '</div>';

        $('.cookbook_step-group').append($html);
        initUploader({'index':length});
    });
    // 删除烹饪步骤
    $('.cookbook_step-group').on('click', '.delStep-btn', function(){
        $(this).parents('.step-group').remove();
    });

    // 自定义验证规则
    form.verify({
        name: function(value){
            if(value == ''){
                return '菜谱名称不能为空';
            }
            if(value.length > 40){
                return '菜谱名称最多为40个字符';
            }
        },
        img_url: function(value){
            if(value == ''){
                return '请上传菜谱封面';
            }
        },
    });

    // 检查食材
    var checkIngredient = function() {
        var status = 1,
            elm = '',
            msg = '';
        $('.ingredients-group').find('.ingredient-group').each(function (i) {
            var name_elm = $(this).find('.ingredient_name');
            var num_elm = $(this).find('.ingredient_num');
            var name = name_elm.val();
            var num = num_elm.val();
            if(name.trim() == ''){
                status = 0;
                elm = name_elm;
                msg = '食材名称不能为空';
                return false; // 跳出循环
            }

            if(num.trim() == ''){
                status = 0;
                elm = num_elm;
                msg = '用量不能为空';
                return false;
            }
        });

        return {'status':status, 'elm':elm, 'msg':msg};
    };

    // 检查烹饪步骤
    var checkCookbookStep = function() {
        var status = 1,
            elm = '',
            msg = '';
        $('.cookbook_step-group').find('.step-group').each(function (i) {
            var img_url_elm = $(this).find('.step_img_url');
            var content_elm = $(this).find('.content');
            var img_url = img_url_elm.val();
            var content = content_elm.val();
            if(img_url.trim() == ''){
                status = 0;
                elm = img_url_elm;
                msg = '请上传步骤图';
                return false; // 跳出循环
            }

            if(content.trim() == ''){
                status = 0;
                elm = content_elm;
                msg = '步骤说明不能为空';
                return false;
            }
        });

        return {'status':status, 'elm':elm, 'msg':msg};
    };

    // 表单提交
    form.on("submit(laySave)", function(data){

        submitForm(data);
    });

    // 表单提交
    function submitForm(data){
        // 检查食材
        var ingredients = checkIngredient();
        if(ingredients.status != 1){
            ingredients.elm.focus();
            layer.msg(ingredients.msg, {icon: 5});
            return;
        }
        // 检查烹饪步骤
        var cookbook_step = checkCookbookStep();
        if(cookbook_step.status != 1){
            cookbook_step.elm.focus();
            layer.msg(cookbook_step.msg, {icon: 5});
            return;
        }

        // 弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});

        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                top.layer.msg(res.msg);
                if(res.code == 1){
                    //layer.closeAll("iframe");
                    var indexLay = parent.layer.getFrameIndex(window.name); // 先得到当前iframe层的索引
                    parent.layer.close(indexLay);

                    // 添加菜谱
                    var cookbook_ids_elm = $(parent.window.frames[0].document).find('.cookbook_ids');
                    var cookbook_ids = cookbook_ids_elm.val();
                    if(cookbook_ids){
                        cookbook_ids = cookbook_ids + ',' + res.data.id;
                    }else{
                        cookbook_ids = res.data.id;
                    }

                    cookbook_ids_elm.val(cookbook_ids);

                    //parent.layui.table.reload('cookbookTableList', {});
                    $(parent.document).find("iframe")[1].contentWindow.location.reload();
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });
    }

});